package com.hly.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.common.constant.ProductConstant;
import com.hly.common.to.SkuHasStockVo;
import com.hly.common.to.SkuReductionTo;
import com.hly.common.to.SpuBoundTo;
import com.hly.common.to.es.SkuEsModel;
import com.hly.common.utils.PageUtils;
import com.hly.common.utils.Query;
import com.hly.common.utils.R;
import com.hly.product.dao.SpuInfoDao;
import com.hly.product.entity.*;
import com.hly.product.feign.SearchFeign;
import com.hly.product.feign.SmsFeign;
import com.hly.product.feign.WmsFeign;
import com.hly.product.service.*;
import com.hly.product.vo.Bounds;
import com.hly.product.vo.EditableTabs;
import com.hly.product.vo.SpuSaveVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDao spuInfoDao;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;

    /**
     * 远程服务调用
     */
    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private SearchFeign searchFeign;
    @Autowired
    private WmsFeign wmsFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String catalogId = (String) params.get("catalogId");
        String brand = (String) params.get("brand");
        String publishStatus = (String) params.get("publishStatus");
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(i -> i.like("spu_name",key)
                    .or()
                    .like("spu_description",key));
        }
        if(StringUtils.isNotEmpty(catalogId)){
            wrapper.eq("catalog_id",catalogId);
        }
        if(StringUtils.isNotEmpty(brand)){
            wrapper.eq("brand_id",brand);
        }
        if(StringUtils.isNotEmpty(publishStatus)){
            wrapper.eq("publish_status",publishStatus);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SpuInfoEntity> getCatalogId() {
        return spuInfoDao.getCatalogId();
    }

    @Override
    public List<EditableTabs> editableTabsBySpuId(Long id) {
        return attrGroupService.getEditableTabsBySpuId(id);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //保存spu_info 基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        this.save(spuInfoEntity);

        //保存商品描述图片信息
        List<SpuInfoDescEntity> spuInfoDescEntityList = spuSaveVo.getDecript().stream().map(dec -> {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setDecript(dec);
            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
            return spuInfoDescEntity;
        }).collect(Collectors.toList());
        spuInfoDescService.saveBatch(spuInfoDescEntityList);
        //保存商品图片集信息
        List<SpuImagesEntity> spuImagesEntityList = spuSaveVo.getImages().stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setImgUrl(image);
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntityList);

        //保存商品的基本属性信息
        List<ProductAttrValueEntity> productAttrValueEntityList = spuSaveVo.getBaseAttrs().stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            if(byId != null && byId.getAttrName() != null){
                productAttrValueEntity.setAttrId(attr.getAttrId());
            }
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        //保存商品的积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        smsFeign.save(spuBoundTo);



        //保存商品的库存销售属性
        spuSaveVo.getSkus().forEach(sku -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            sku.getImages().stream().filter(images -> images.getDefaultImg()==1 ).forEach(images -> {
                skuInfoEntity.setSkuDefaultImg(images.getImgUrl());
            });
            skuInfoService.save(skuInfoEntity);

            //Sku的图片集
            List<SkuImagesEntity> skuImages = sku.getImages().stream().map(images -> {
                SkuImagesEntity imagesEntity = new SkuImagesEntity();
                imagesEntity.setImgUrl(images.getImgUrl());
                imagesEntity.setDefaultImg(images.getDefaultImg());
                imagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return imagesEntity;
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImages);
            //Sku的销售属性
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = sku.getAttr().stream().map(attr -> {
                ArrayList<String> strings = new ArrayList<>();
                StringTokenizer stringTokenizer = new StringTokenizer(attr.getAttrValue(), ";");
                while (stringTokenizer.hasMoreTokens()){
                    strings.add(stringTokenizer.nextToken());
                }
                //自定义销售属性
                strings.stream().forEach(value -> {
                    AttrEntity byId = attrService.getById(attr.getAttrId());
                    if (byId.getValueSelect().indexOf(value) == -1){
                        byId.setValueSelect(byId.getValueSelect()+";"+value);
                        attrService.updateById(byId);
                    }
                });

                SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, saleAttrValueEntity);
                saleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return saleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

            //保存Sku 的打折、满减、会员价格信息
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            smsFeign.saveInfo(skuReductionTo);

        });



    }

    /**
     * 商品上架业务逻辑
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //拿到商品的规格属性
        List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueService.baseAttrListforspu(spuId);
        productAttrValueEntityList.stream().forEach(ProductAttrValueEntity::getAttrId);
        List<Long> attrIds = productAttrValueEntityList.stream().map(productAttrValueEntity -> productAttrValueEntity.getAttrId()).collect(Collectors.toList());
        List<Long> attrIdsList = attrService.selectSearchAttrIds(attrIds);
        Set<Long> attrIdsSet = new HashSet<>(attrIdsList);
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntityList.stream().filter(productAttrValueEntity -> attrIdsSet.contains(productAttrValueEntity.getAttrId())).map(productAttrValueEntity -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            attrs.setAttrId(productAttrValueEntity.getAttrId());
            attrs.setAttrName(productAttrValueEntity.getAttrName());
            attrs.setAttrValue(productAttrValueEntity.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());

        //获取商品所有sku的是否有库存信息
        List<Long> skuIds = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId)).stream().map(skuInfoEntity -> skuInfoEntity.getSkuId()).collect(Collectors.toList());
        Map<Long,Boolean> skuHasStock = null;
        try{
            R r = wmsFeign.jubStockBySkuId(skuIds);
            if(r.getCode() == 0){
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
                skuHasStock = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, skuHasStock2 -> skuHasStock2.getHasStock()));
            }
        }catch (Exception e){
            log.error("error，服务调用失败！原因{}",e);
        }

        Map<Long, Boolean> finalStockMap = skuHasStock;
        //封装好前面获取的信息以及对应的Sku、品牌信息、分类信息
        List<SkuEsModel> skuEsModelList = skuInfoService.selectListBySpuId(spuId).stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            CategoryEntity categoryById = categoryService.getById(skuInfoEntity.getCatalogId());
            BrandEntity brandById = brandService.getById(skuInfoEntity.getBrandId());
            //分类信息
            skuEsModel.setCatalogId(categoryById.getCatId());
            skuEsModel.setCatalogName(categoryById.getName());
            //品牌信息
            skuEsModel.setBrandId(brandById.getBrandId());
            skuEsModel.setBrandImg(brandById.getLogo());
            skuEsModel.setBrandName(brandById.getName());
            //Sku信息
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            //判断是否有库存
            if(finalStockMap != null && finalStockMap.get(skuInfoEntity.getSkuId()) != null){
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }else {
                skuEsModel.setHasStock(false);
            }

            //设置热点
            skuEsModel.setHotScore(0L);

            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        R r = searchFeign.productStatusUp(skuEsModelList);
        if(r.getCode() == 0){
            this.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {

        }


    }

    /**
     * 根据商品spuId ,修改商品上架状态
     * @param spuId
     * @param code
     */
    @Override
    public void updateSpuStatus(Long spuId, int code) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setId(spuId);
        spuInfoEntity.setPublishStatus(code);
        this.updateById(spuInfoEntity);
    }

}